package cn.jiedh.app.meiweidk.baseadapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;

/**
 * @name：RecyclerView通用的ViewHolder
 * @author：司马林
 * @phone：18423134135
 * @createTime：2017/10/20
 */

public class BaseViewHolder extends RecyclerView.ViewHolder {
    private SparseArray<View> mViews = new SparseArray<>();

    public BaseViewHolder(View itemView) {
        super(itemView);
    }

    public static BaseViewHolder get(Context mContext, ViewGroup parent, int layoutId) {
        View itemView = LayoutInflater.from(mContext).inflate(layoutId, parent, false);
        return new BaseViewHolder(itemView);
    }

    public static BaseViewHolder get(View headerView) {
        if (headerView != null) {
            return new BaseViewHolder(headerView);
        } else {
            return null;
        }
    }

    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = (View) itemView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public BaseViewHolder setText(int viewId, String text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    public BaseViewHolder setText(int viewId, SpannableString text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    public BaseViewHolder setImageUrl(int viewId, String url) {
        ImageView img = getView(viewId);
        LoadUtils.loadImage(img.getContext(),url,img);
//        Glide.with(img.getContext()).load(url).placeholder(R.drawable.green_loading).error(R.drawable.load_fail).into(img);
        return this;
    }

    public BaseViewHolder setVisibility(int viewId,boolean isVisible){
        View view=getView(viewId);
        view.setVisibility(isVisible?View.VISIBLE:View.GONE);
        return this;
    }

    public BaseViewHolder setImageRes(int viewId,int resId){
        ImageView img = getView(viewId);
        img.setImageResource(resId);
        return this;
    }
    public BaseViewHolder setOnclickListener(int viewId, View.OnClickListener listener) {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }
}
